package com.neborosoft.android.gui.search;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import com.neborosoft.FlyingDog.R;
import com.neborosoft.android.gui.AutoKeyboardHandlingEditTextView;
import com.neborosoft.android.gui.Gui;
import com.neborosoft.android.gui.adapters.listview.OnItemClick;
import com.neborosoft.android.gui.adapters.listview.TextViewArrayAdapter;
import com.neborosoft.android.threading.AndroidOnHostThreadExecutor;
import com.neborosoft.lib.API_8.Collections;
import com.neborosoft.lib.handlers.OnHardwareBackPressed;
import com.neborosoft.lib.threading.AbstractAsyncTask;
import com.neborosoft.lib.threading.OnHostThreadExecutor;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 27.12.12
 * Time: 13:55
 * To change this template use File | Settings | File Templates.
 */
public class SearchDialog extends LinearLayout {
    public interface SearchHandler{
        Object search(String query);
        void onSearchFinished(Object searchResult);
        void onSkipSearch();
        List getSuggestions(String query);
    }

    private static final Executor EXECUTOR = Executors.newSingleThreadExecutor();
    private static final OnHostThreadExecutor ON_HOST_THREAD_EXECUTOR = new AndroidOnHostThreadExecutor();

    private LinearLayout searchLayout;
    private ImageButton searchButton;
    private AbsListView suggestionsListView;
    private AutoKeyboardHandlingEditTextView searchEditField;

    private TextViewArrayAdapter suggestionsAdapter;

    private AbstractAsyncTask<String, List> suggestionsGettingTask =
            new AbstractAsyncTask<String, List>(ON_HOST_THREAD_EXECUTOR)
    {
        @Override
        protected List doInBackground(String query) {
            return searchHandler.getSuggestions(query);
        }

        @Override
        protected void onPostExecute(List suggestions) {
            if(suggestions == null){
                suggestions = Collections.emptyList();
            }
            suggestionsAdapter.setElements(suggestions);
        }
    };

    private SearchHandler searchHandler;

    private AbstractAsyncTask<String, Object> searchingTask =
            new AbstractAsyncTask<String, Object>(ON_HOST_THREAD_EXECUTOR) {
        @Override
        protected Object doInBackground(String query) {
            return searchHandler.search(query);
        }

        @Override
        protected void onPostExecute(Object searchResult) {
            searchHandler.onSearchFinished(searchResult);
        }
    };

    public SearchHandler getSearchHandler() {
        return searchHandler;
    }

    public void setSearchHandler(SearchHandler searchHandler) {
        this.searchHandler = searchHandler;
    }

    public String getQuery(){
        return searchEditField.getText().toString();
    }

    public void setQuery(CharSequence query){
        searchEditField.setText(query);
    }

    private TextWatcher onQueryChanged = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String query = s.toString();
            suggestionsGettingTask.execute(query, EXECUTOR);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    public void search(String query){
        searchingTask.execute(query, EXECUTOR);
    }

    public void search(){
        String query = getQuery();
        search(query);
    }

    private void switchLayoutVisibilities(){
        Gui.swapViewVisibilities(searchLayout,searchButton);
    }

    private OnClickListener onSearchButtonClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switchLayoutVisibilities();
            searchEditField.startEditing();
        }
    };

    private OnHardwareBackPressed onBackWhenKeyboardIsShown = new OnHardwareBackPressed() {
        @Override
        public void onBack() {
            switchLayoutVisibilities();
            searchHandler.onSkipSearch();
        }
    };

    OnClickListener onSearchSubmit = new OnClickListener() {
        @Override
        public void onClick(View v) {
            search();
            switchLayoutVisibilities();
        }
    };

    private void init(final Context context){
        inflate(context, R.layout.search_dialog, this);

        searchLayout = (LinearLayout)findViewById(R.id.searchDialogSearchLayout);

        suggestionsListView = (AbsListView)findViewById(R.id.searchDialogSuggestionsList);

        searchButton = (ImageButton)findViewById(R.id.searchDialogSearchButton);
        searchButton.setOnClickListener(onSearchButtonClick);

        searchEditField = (AutoKeyboardHandlingEditTextView)findViewById(R.id.searchDialogSearchEditField);
        searchEditField.addTextChangedListener(onQueryChanged);
        searchEditField.setOnEnterClickListener(onSearchSubmit);
        searchEditField.setOnHardwareBackPressedListener(onBackWhenKeyboardIsShown);

        suggestionsAdapter = new TextViewArrayAdapter(context, suggestionsListView);
        suggestionsAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onClick(Object suggestion, View view, int position) {
                String suggestionText = suggestion.toString();
                search(suggestionText);
                switchLayoutVisibilities();
                searchEditField.hideKeyboard();
            }
        });
        Gui.setAdapter(suggestionsListView, suggestionsAdapter);

        setFocusable(true);
        setFocusableInTouchMode(true);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_SEARCH){
            searchButton.performClick();
        }

        return super.onKeyUp(keyCode, event);
    }

    public SearchDialog(Context context) {
        super(context);
        init(context);
    }

    public SearchDialog(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
}
